package dtd.PHS.VND_ExchangeRate.ui;

import java.util.ArrayList;

import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;
import dtd.PHS.VND_ExchangeRate.R;
import dtd.PHS.VND_ExchangeRate.data.ListRates;
import dtd.PHS.VND_ExchangeRate.data.MyDate;
import dtd.PHS.VND_ExchangeRate.data.RateItem;
import dtd.PHS.VND_ExchangeRate.data.VNExDatabase;
import dtd.PHS.VND_ExchangeRate.ui.adapters.ChooseCurrencyAdapter;
import dtd.PHS.VND_ExchangeRate.utils.Helpers;

public class SendSmsView extends RequestableFrameLayout {

	private ListView listview;
	private Button btShareSMS;
	private ChooseCurrencyAdapter adapter;
	private ListRates listRates;
	private Button btShareEmail;
	private Activity hostedActivity;

	public SendSmsView(Activity activity) {
		super(activity.getApplicationContext());
		this.hostedActivity  = activity;
	}

	@Override
	public void createViews() {
		Helpers.inflateView(R.layout.send_sms_act, this);
		main_frames = (FrameLayout) findViewById(R.id.main_frames);
		listview = (ListView) findViewById(R.id.lvChooseCurrencies);
		createShareButton();
	}
	private void createShareButton() {
		btShareSMS = (Button) findViewById(R.id.btSharePerSMS);
		btShareSMS.setOnClickListener( new MyClickListener() {
			@Override
			protected void broadCastResult(String content) {
				Helpers.broadcastSMSIntent(content);
			}
		});		
		
		btShareEmail = (Button) findViewById(R.id.btSharePerEmail);
		btShareEmail.setOnClickListener( new MyClickListener() {
			@Override
			protected void broadCastResult(String content) {
				Helpers.broadcastEmailIntent(hostedActivity, content);
			}
		});		
	}

	private void saveSelectedRates(ArrayList<RateItem> rates) {
		String str = "";
		for(int i = 0 ; i < rates.size() ; i++) {
			RateItem item = rates.get(i);
			str += item.getCurrencyName();
			if (  i != rates.size() - 1 ) {
				str += ",";
			}
		}
		Helpers.setPreference(Helpers.PREF_SELECTED_CURRENCIES, str);
	}

	
	private void createListView() {
	    listview = (ListView) findViewById(R.id.lvChooseCurrencies);
	    adapter = new ChooseCurrencyAdapter(listRates);
	    listview.setAdapter(adapter);
	}

	@Override
	public void onGetDataCompleted(Object data) {
		if ( data instanceof ListRates ) {
			listRates = (ListRates) data;
			createListView();
		}
		
	}

	@Override
	public void onGetDataError(Exception e) {
	}

	abstract class MyClickListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			ListRates rates = adapter.getSelectedRates();
			MyDate date = VNExDatabase.getDate();
			String content = Helpers.createSMSContent(rates, date.toString());
			saveSelectedRates( rates );
			broadCastResult(content);
		}

		protected abstract void broadCastResult(String content);
		
	}

}
